<#include "/common/_header.html" />
<style>
    #photo{ width:auto; height:auto; margin:auto; margin-top:0.5rem;}
    #photo img{width:77px; height:77px;margin-right:5px;}
    #chooseImg{position: absolute;z-index: 1;top: 0; left: 0;width:77px;height:77px;opacity: 0;}
    .file_box {width:77px; height:77px;margin-right:5px;display:-webkit-inline-box;position:relative;
			   background-image:url('${path}/resource/images/img_add.png');}
	.floatBtn { background: #f16522;display: block;  position: fixed;  right: 15px;  bottom: 10px;  width: 45px;  height: 45px; border: 1px solid #f16522;  box-sizing: border-box;  -webkit-box-sizing: border-box;  border-radius: 50%;  -webkit-border-radius: 50%;  -moz-border-radius: 50%;  font-size: 12px;  color: #999999;  z-index: 99;  text-align: center; }
	.floatBtn>i{margin-top: 1rem;color:#fff;font-size:1.5rem;}
	.floatBtn:active{ background:#f16522; color: #fff; border: 1px solid #fff;}
	.floatBtn_t2 { background: #f16522;display: block;  position: fixed;  right: 15px;  bottom: 65px;  width: 45px;  height: 45px; border: 1px solid #f16522;  box-sizing: border-box;  -webkit-box-sizing: border-box;  border-radius: 50%;  -webkit-border-radius: 50%;  -moz-border-radius: 50%;  font-size: 12px;  color: #999999;  z-index: 99;  text-align: center; }  
	.floatBtn_t2>i{margin-top: 1rem;color:#fff;font-size:1.5rem;}
	.floatBtn_t2:active{ background:#f16522; color: #fff; border: 1px solid #fff;}
</style>
<div class="page-group"><!-- 页面组 -->
	<div class="page page-current"><!-- 页面组中的每一个页面，可以互相跳转 -->
		<header class="bar bar-nav"><!-- 每个页面的头部 -->
			<h1 class="title" style="font-size: 1rem;">${sellervo.sellerName}-新增</h1>
		</header>
		<#include "/common/_navbar.html" /><!-- 每个页面的底部 -->
		<div class="content native-scroll"><!-- 每个页面的内容区域 -->
			<form id="bbsform" action="${path}/discounts/addEntity" method="post">
			  <div class="content-block" style="margin-bottom: -1.5rem;margin-top: 0.5rem;font-size: 0.5rem;text-align: right;">
			  	<#if (sellervo.coins!0) < (sellervo.coinsPerBbs!0)><span class="pull-left" style="color:red">！金币不足</span></#if>
			  	<span>本次发布消耗金币:${sellervo.coinsPerBbs!0} | 总金币:${sellervo.coins!0}</span>
			  </div>
			  <div class="list-block">
			    <ul>
			      <li>
			        <div class="item-content">
			          <div class="item-inner" style="margin-left:-0.25rem;">
			            <div class="item-input">
			              <textarea name="comments" onKeyDown="textCounter(this)" placeholder="简单描述优惠信息..."></textarea>
			              <span id="remLen" class="pull-right" style="color:#cccccc;font-size: 0.5rem;">0/100</span>
			            </div>
			          </div>
			        </div>
			      </li>
			      <li>
			        <div class="item-content">
			          <div class="item-inner" style="margin-left:-0.25rem;">
			            <div class="item-title label">开始生效</div>
			            <div class="item-input" style="display: inline-flex;">
			              <select name="activeStart">
			              	<option value="1" selected>立即</option>
			              	<option value="2">明天7点</option>
			              	<option value="3">后天7点</option>
			              </select>
			              <span class="pull-right iconfont icon-unfold" style="color:#ccc"></span>
			            </div>
			          </div>
			        </div>
			      </li>
			      <li>
			        <div class="item-content">
			          <div class="item-inner" style="margin-left:-0.25rem;">
			            <div class="item-title label">持续</div>
			            <div class="item-input" style="display: inline-flex;">
			              <select name="duration">
			              	<option value="1" selected>1天</option>
			              	<option value="2">2天</option>
			              	<option value="3">3天</option>
			              	<option value="4">4天</option>
			              	<option value="5">5天</option>
			              	<option value="6">6天</option>
			              	<option value="7">7天</option>
			              </select>
			              <span class="pull-right iconfont icon-unfold" style="color:#ccc"></span>
			            </div>
			          </div>
			        </div>
			      </li>			      
			    </ul>
			  </div><!-- end of list-block -->
			  <div class="content-block" style="margin:-0.5rem 0 -0.5rem -0.3rem;">
		        <div id="photo">
		        	<div class="file_box">
		        		<input type="file" id="chooseImg" accept="image/*" onchange="chooseImgs(this)"/>
		        	</div>
		        </div>
			  </div>
			</form>														
		</div><!-- end of content -->
		<#if (sellervo.coinsPerBbs!0) <= (sellervo.coins!0)>
		<a href="javascript:void(0)" class="floatBtn"  id="_backword">
		    <i class="iconfont icon-back"></i>
		</a>
		<a href="javascript:void(0)" class="floatBtn_t2"  id="_saveBbs">
		    <i class="iconfont icon-check"></i>
		</a>
		</#if>
	</div><!-- end of page -->
</div><!-- end of page group -->
<#include "/common/_footer.html" />
<script src="${path}/resource/js/exif.js"></script>
<script>
$(function(){
	$("#_backword").click(function(){
		location.href = "${path}/discounts";
	});
	$("#_saveBbs").click(function(){
		if(parseInt('${sellervo.coins!0}')<parseInt('${sellervo.coinsPerBbs!0}')){
			$.toast("金币不够");
			return;
		}else if(parseInt('${sellervo.allowedDeployNum!2}')<=parseInt('${sellervo.deployedNum!0}')){
			$.toast("今天的发布优惠数量已用完。");
			return;
		}else if($("textarea[name='comments']").val().trim()==''){
			$.toast("请填写内容");
			return;
		}else if($("#photo").children().length==0){
			$.toast("请添加照片");
			return;
		}
		$.showIndicator();
		$("#bbsform").submit();
	});
});
function chooseImgs(obj){
	if($("#photo img").length==2){
		$.alert("最多可以上传2张照片。");
		return ;
	}
	if(obj.files!=null && obj.files.length>0){
		$.showIndicator();
		readImg(obj.files,obj.files.length,0);
	}
}
function readImg(allfile,remainFile,fileindex){
	var maxSize = 100 * 1024;//100KB，大于100KB将进行压缩
	var file = allfile[fileindex];
	remainFile--;
	fileindex++;
    var orientation;
	EXIF.getData(file,function(){
		orientation=EXIF.getTag(this,'Orientation');
		var reader = new FileReader();
	    reader.onload = function(){
	    	var result = this.result;   //result为data url的形式
	    	getImgData(this.result,orientation,function(data){
	    		//这里可以使用校正后的图片data了
	            img = new Image();
	            img.src = data;
	            //console.log("compressImg.size="+data.length);
	            if(data.length < maxSize){
	                previewImg(data);
	                if(remainFile>0){
	                	readImg(allfile,remainFile,fileindex);
	                }
	            } else {
	            	var comdata = compressImg(img);
	                previewImg(comdata);
	                if(remainFile>0){
	                	readImg(allfile,remainFile,fileindex);
	                }
	            }
			});
	    }
	    reader.readAsDataURL(file);
	});
}
function previewImg(imgData){
    //追加到图片列表
	var imgNode = document.createElement("img");
    var id = "img_"+new Date().getTime();
	imgNode.src=imgData;
	imgNode.id=id;
	imgNode.onclick = function(){
		picdet(imgData,id);
	};
	var hiddenNode = document.createElement("input");
	hiddenNode.type="hidden";
	hiddenNode.name="base64Img";
	hiddenNode.id="hid_"+id;
	hiddenNode.value=imgData;
	$(hiddenNode).insertBefore($(".file_box"));
	$(imgNode).insertBefore($(".file_box"));
	$.hideIndicator();
}
//处理iphone拍照图片旋转问题
function getImgData(img,dir,next){
	var image=new Image();
	image.src=img;
	image.onload=function(){
		var degree=0,drawWidth,drawHeight,width,height;
		drawWidth=this.naturalWidth;
		drawHeight=this.naturalHeight;
		//以下改变一下图片大小
		var maxSide = Math.max(drawWidth, drawHeight);
		if (maxSide > 1024) {
			var minSide = Math.min(drawWidth, drawHeight);
			minSide = minSide / maxSide * 1024;
			maxSide = 1024;
			if (drawWidth > drawHeight) {
				drawWidth = maxSide;
				drawHeight = minSide;
			} else {
				drawWidth = minSide;
				drawHeight = maxSide;
			}
		}
		var canvas=document.createElement('canvas');
		canvas.width=width=drawWidth;
		canvas.height=height=drawHeight;
		var context=canvas.getContext('2d');
		//判断图片方向，重置canvas大小，确定旋转角度，iphone默认的是home键在右方的横屏拍摄方式
		switch(dir){
			//iphone横屏拍摄，此时home键在左侧
			case 3:
			degree=180;
			drawWidth=-width;
			drawHeight=-height;
			break;
			//iphone竖屏拍摄，此时home键在下方(正常拿手机的方向)
			case 6:
			canvas.width=height;
			canvas.height=width;
			degree=90;
			drawWidth=width;
			drawHeight=-height;
			break;
			//iphone竖屏拍摄，此时home键在上方
			case 8:
			canvas.width=height;
			canvas.height=width;
			degree=270;
			drawWidth=-width;
			drawHeight=height;
			break;
		}
		//使用canvas旋转校正
		context.rotate(degree*Math.PI/180);
		context.drawImage(this,0,0,drawWidth,drawHeight);
		//返回校正图片
		var picRate = 0.1; //3M以上
		if(image.src.length >= 1 * 1024 * 1024 && image.src.length < 3 * 1024 * 1024){//大于1M，小于3M
			picRate = 0.2;
		}else if(image.src.length < 1 * 1024 * 1024){//小于1M
			picRate = 0.3;
		}
		//console.log("getImgData.picRate="+picRate);
		//console.log("getImgData.size="+image.src.length);
		next(canvas.toDataURL("image/jpeg",picRate));
	}
}
//图片压缩
function compressImg(img){
	var canvas=document.createElement("canvas");
	var ctx=canvas.getContext("2d");
	var tCanvas=document.createElement("canvas");
	var tctx=tCanvas.getContext("2d");
    var initSize = img.src.length;
    var width = img.width;
    var height = img.height;
    //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
    var ratio;
    if ((ratio = width * height / 4000000)>1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
    }else {
        ratio = 1;
    }
    canvas.width = width;
    canvas.height = height;
    //铺底色
    ctx.fillStyle = "#fff";
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    //如果图片像素大于100万则使用瓦片绘制
    var count;
    if ((count = width * height / 1000000) > 1) {
        count = ~~(Math.sqrt(count)+1); //计算要分成多少块瓦片
		//计算每块瓦片的宽和高
        var nw = ~~(width / count);
        var nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (var i = 0; i < count; i++) {
            for (var j = 0; j < count; j++) {
                tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
            }
        }
    } else {
        ctx.drawImage(img, 0, 0, width, height);
    }
    //进行最小压缩
    var picRate = 0.1; //3M以上
	if(img.src.length >= 1 * 1024 * 1024 && img.src.length < 3 * 1024 * 1024){//大于1M，小于3M
		picRate = 0.2;
	}else if(img.src.length < 1 * 1024 * 1024){//小于1M
		picRate = 0.3;
	}
	console.log("compressImg.picRate="+picRate);
    var ndata = canvas.toDataURL('image/jpeg', picRate);
    console.log('压缩前：' + initSize);
    console.log('压缩后：' + ndata.length);
    console.log('压缩率：' + ~~(100 * (initSize - ndata.length) / initSize) + "%");
    tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
    return ndata;
}
function picdet(imgsrc,imgid){
	var popupHTML = '<div class="popup" style="justify-content:center;align-items:center;background-color:#000000;">'+
      	"<a onclick='detPic(\""+imgid+"\")' style='position:absolute;float:right;z-index:100;right:1rem;top:0;'><span class='iconfont icon-delete' style='font-size:1.5rem;'></span></a>"+
		'<div class="close-popup">'+
			'<img src="'+imgsrc+'" style="max-width:100%;height:auto;">'+
		'</div>'
    '</div>'
	$.popup(popupHTML);
    $(".popup").css("display","flex");
}
function detPic(imgid){
	$.closeModal();
	$("#hid_"+imgid).remove();
	$("#"+imgid).remove();
}
function textCounter(obj){
	var maxlimit = 100;
	if ($(obj).val().length > maxlimit){
		$(obj).val($(obj).val().substring(0, maxlimit));
	}
	$("#remLen").text($(obj).val().length + "/" + maxlimit); 
}
</script>